package com.xbb.controller.sys;

import com.xbb.common.RespResult;
import com.xbb.constant.SessionConstant;
import com.xbb.entity.Notice;
import com.xbb.entity.User;
import com.xbb.mapper.NoticeMapper;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/sys/notice")
public class SysNoticeController {

    private String prefix = "/sys/notice/";

    @Resource
    private NoticeMapper noticeMapper;

    // 公告管理
    @RequestMapping("/manage.html")
    public String manageHtml() {
        return prefix + "notice";
    }

    // 分页数据
    @ResponseBody
    @RequestMapping("/data")
    public RespResult data(@RequestParam("page") int page,
                           @RequestParam("limit") int limit,
                           @RequestParam(value = "title", required = false, defaultValue = "") String title) {
        if (title.equals("")) title = null;
        List<Notice> noticeList = noticeMapper.selectListByPaging((page - 1) * limit, limit, title);
        int count = noticeMapper.selectCountByPaging(title);
        RespResult respResult = new RespResult();
        respResult.success(noticeList, count);
        return respResult;
    }

    // 添加
    @RequestMapping("/add.html")
    public String addHtml() {
        return prefix + "add";
    }

    @ResponseBody
    @RequestMapping("/add")
    public RespResult add(@RequestBody Notice notice, HttpSession session) {
        User user = (User) session.getAttribute(SessionConstant.KEY_USER);
        notice.setUserId(user.getId());
        notice.setCreatTime(new Date());
        noticeMapper.insertSelective(notice);
        return new RespResult();
    }

    // 编辑
    @RequestMapping("/edit.html")
    public String editHtml(@RequestParam("id") int id, Model model) {
        Notice notice = noticeMapper.selectByPrimaryKey(id);
        model.addAttribute("notice", notice);
        return prefix + "edit";
    }

    @ResponseBody
    @RequestMapping("/edit")
    public RespResult edit(@RequestBody Notice notice) {
        noticeMapper.updateByPrimaryKeySelective(notice);
        return new RespResult();
    }

    // 查看详情
    @RequestMapping("/item.html")
    public String itemHtml(@RequestParam("id") int id, Model model) {
        Notice notice = noticeMapper.selectById(id);
        model.addAttribute("notice", notice);
        return prefix + "item";
    }

    // 删除
    @ResponseBody
    @RequestMapping("/delete")
    public RespResult delete(@RequestBody int id) {
        noticeMapper.deleteByPrimaryKey(id);
        return new RespResult();
    }

}
